<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/12/24
 * Time: 11:14
 */

namespace app\crm\traits;

use Qiniu\Storage\UploadManager;
use Qiniu\Auth;

trait Upload
{
    /**
     * @param $type
     * @return bool
     */
    public function isImg($type)
    {
        $typeArr = ['image/jpg', 'image/png', 'image/gif', 'image/jpeg', 'image/bmp', 'image/webp'];
        if (in_array($type, $typeArr)) {
            return true;
        }
        return false;
    }

    public function getExtensionName($file)
    {
        $fileName = $file['name'];
        $arr = explode('.', $fileName);
        return $arr[count($arr) - 1];
    }

    public function upload($file, $bathPath)
    {
        $moveDir = ROOT_PATH . 'public' . $bathPath;
        if (!file_exists($moveDir)) {
            @mkdir($moveDir, 0766, true);
        }
        $extensionName = $this->getExtensionName($file);
        $fileName = substr(md5($file['name'] . time()), 0, 16) . '.' . $extensionName;
        $filePath = $moveDir . $fileName;
        move_uploaded_file($file['tmp_name'], $filePath);
        return $bathPath . $fileName;
    }

    public function cloudUpload($fileName, $filePath)
    {
        $accessKey = config('qiniu_access_key');
        $secretKey = config('qiniu_secret_key');
        $upManager = new UploadManager();
        $auth = new Auth($accessKey, $secretKey);
        $bucket = config('qiniu_default_bucket');
        $token = $auth->uploadToken($bucket);
        try {
            $res = $upManager->putFile($token, $fileName, $filePath);
        } catch (\Exception $e) {
            return false;
        }
        if ($res) {
            if (isset($res[0]['key'])) {
                $fileUrl = config('qiniu_url') . $res[0]['key'];
                return $fileUrl;
            }
            return false;
        }
        return false;
    }
}